package com.eboss2.sbs.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.codbking.widget.DatePickDialog;
import com.codbking.widget.OnSureLisener;
import com.codbking.widget.bean.DateType;
import com.eboss2.sbs.R;
import com.eboss2.sbs.activity.base.BaseActivity;
import com.eboss2.sbs.adapter.ProfitListAdapter;
import com.eboss2.sbs.config.Config;
import com.eboss2.sbs.http.HttpUtil;
import com.eboss2.sbs.model.BonusDay;
import com.eboss2.sbs.model.ProfitInfo;
import com.eboss2.sbs.model.ProfitInfoList;
import com.eboss2.sbs.myapplication.MyApplication;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.loopj.android.http.RequestParams;
import com.mytools.tool.activityManager.MyActivityManager;
import com.mytools.tool.utils.TimeUtil;
import com.tool.utils.utils.StringUtils;
import com.tool.utils.view.MyListView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MyProfitDetailActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

	private PullToRefreshScrollView pullToRefreshScrollView;
	private MyListView listview;
	private List<ProfitInfo> datas = new ArrayList<>();
	private ProfitListAdapter adapter;
	private int page = 1;
	private int rows = Config.ROWS;

	private TextView tv_mcht_name;

	private AlertDialog dialog_panel;
	private TextView tv_date_to, tv_date_from;
	private LinearLayout ly_time_zone;

	private Date panel_dateFrom = new Date();
	private Date panel_dateTo = new Date();

	private String startTime = "";
	private String endTime = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.activity_my_profit_detail);
		MyActivityManager.getInstance().addActivity(this);
		initView();
	}

	private void initView(){
		RelativeLayout relativeLayout = relativeLayout(R.id.lv_heard);
		relativeLayout.setBackgroundColor(getResources().getColor(R.color.statusBar));
		showView(R.id.titleback_btn_back, true);
		setTvText(R.id.tv_title, "分润明细列表");
		showView(R.id.next_sure, false);
		setTvText(R.id.next_sure, "筛选");
		findViewById(R.id.next_sure).setOnClickListener(this);
		findViewById(R.id.titleback_btn_back).setOnClickListener(this);

		tv_mcht_name = textView(R.id.tv_mcht_name);



		startTime = TimeUtil.getStringFromDate(new Date(), "yyyy-MM-dd");
		endTime = TimeUtil.getStringFromDate(new Date(), "yyyy-MM-dd");





		pullToRefreshScrollView = (PullToRefreshScrollView) findViewById(R.id.pullToRefreshScrollView);
		pullToRefreshScrollView.setOnRefreshListener(new MyProfitDetailActivity.MyOnRefreshListener());
		pullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
		listview = (MyListView) findViewById(R.id.listview);
		listview.setOnItemClickListener(this);

//		for (int i = 0; i < 10; i++){
//			ProfitInfo profitInfo = new ProfitInfo();
//			profitInfo.setAmt(11111);
//			profitInfo.setNum(333);
//			profitInfo.setTime("2018-01-01");
//			datas.add(profitInfo);
//		}


		adapter = new ProfitListAdapter(this, datas);
		listview.setAdapter(adapter);

	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
		startActivity(new Intent(mContext, MyProfitDetailItemListActivity.class).putExtra("time", datas.get(i).getStatisDate()));
	}


	class MyOnRefreshListener implements PullToRefreshBase.OnRefreshListener2<ScrollView> {
		@Override
		public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
			pullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
			String label = DateUtils.formatDateTime(mContext, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
			refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
			refreshData();
		}
		@Override
		public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
			if (datas.size() == 0) {
				handler.postDelayed(new Runnable() {

					@Override
					public void run() {
						showErrorMsg("没有更多了");
						pullToRefreshScrollView.onRefreshComplete();
					}
				}, 1000);
			} else {
				page++;
				getdata();
			}
		}
	}



	@Override
	protected void onResume() {
		super.onResume();
		refreshData();
	}


	private void refreshData(){
		datas.clear();
		page = 1;
		getdata();
	}

	private void getdata(){
		showProgress("加载中...");

		String url = Config.SBS_SHOP_MONTH_DETAIL_LIST;
		RequestParams params = new RequestParams();
		params.put("shopId", MyApplication.getmInstance().getLoginMEntity().getShopid() + "");
//		params.put("startTime",startTime);
//		params.put("endTime",endTime);
		params.put("pageNo", page);
		params.put("pageSize", "15");

		HttpUtil.get(url, params, new HttpUtil.RequestListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void success(String response) {
				disShowProgress();
				try {

					JSONObject result = new JSONObject(response);
					if (!result.optBoolean("status")) {
						showErrorMsg(result.getString("message"));
						// 刷新完成
						pullToRefreshScrollView.onRefreshComplete();
						return;
					}

					Gson gson = new Gson();
					// json数据转换成List
					ProfitInfoList txRecord = gson.fromJson(result.optString("data"), new TypeToken<ProfitInfoList>() {
					}.getType());

					if (txRecord == null) {
						pullToRefreshScrollView.onRefreshComplete();
						return;
					}

//					tvTxCount.setText(txRecord.getDateTime());
//					tvTxTotalNum.setText(txRecord.getVerifyBonusNumber() + "");
//					tvTxTotalCount.setText(txRecord.getVerifyCount() + "");
					tv_mcht_name.setText(StringUtils.formatIntMoney(txRecord.getAllGetAmount()));
//					tvMemberNum.setText(txRecord.getVerifyMemberCount()+"");

					if (txRecord.getShopProfitList().size() > 0) {
						datas.addAll(txRecord.getShopProfitList());
						if (datas.size() > 0) {
							linearLayout(R.id.id_no_data).setVisibility(View.GONE);
							listview.setVisibility(View.VISIBLE);
						} else {
							linearLayout(R.id.id_no_data).setVisibility(View.VISIBLE);
							listview.setVisibility(View.GONE);
						}

					} else {
						if (datas.size() > 0) {

							linearLayout(R.id.id_no_data).setVisibility(View.GONE);
							listview.setVisibility(View.VISIBLE);
							handler.postDelayed(new Runnable() {

								@Override
								public void run() {
									showErrorMsg("没有更多数据");
								}
							}, 1000);
						} else {
							linearLayout(R.id.id_no_data).setVisibility(View.VISIBLE);
							listview.setVisibility(View.GONE);
						}
					}
					// 刷新完成
					pullToRefreshScrollView.onRefreshComplete();
					adapter.notifyDataSetChanged();


				} catch (Exception e) {
					e.getMessage();
					pullToRefreshScrollView.onRefreshComplete();
				}
			}

			@Override
			public void failed(Throwable error) {
				disShowProgress();
				showE404();
				pullToRefreshScrollView.onRefreshComplete();
			}
		});
	}





	@Override
	public void onClick(View v) {
		Intent intent = new Intent();
		switch (v.getId()) {
			case R.id.titleback_btn_back:
				finish();
				break;
			case R.id.tv_date_from:
				DatePickDialog dialog = new DatePickDialog(this);
				//设置上下年分限制
				dialog.setYearLimt(5);
				//设置标题
				dialog.setTitle("选择时间");
				//设置类型
				dialog.setType(DateType.TYPE_YMD);
				//设置消息体的显示格式，日期格式
				dialog.setMessageFormat("yyyy-MM-dd");
				//设置选择回调
				dialog.setOnChangeLisener(null);
				//设置点击确定按钮回调
				dialog.setOnSureLisener(new OnSureLisener() {
					@Override
					public void onSure(Date date) {
						tv_date_from.setText(TimeUtil.getStringFromDate(date, "yyyy-MM-dd"));
					}
				});
				dialog.show();
				break;
			case R.id.tv_date_to:
				DatePickDialog dialog2 = new DatePickDialog(this);
				//设置上下年分限制
				dialog2.setYearLimt(5);
				//设置标题
				dialog2.setTitle("选择时间");
				//设置类型
				dialog2.setType(DateType.TYPE_YMD);
				//设置消息体的显示格式，日期格式
				dialog2.setMessageFormat("yyyy-MM-dd");
				//设置选择回调
				dialog2.setOnChangeLisener(null);
				//设置点击确定按钮回调
				dialog2.setOnSureLisener(new OnSureLisener() {
					@Override
					public void onSure(Date date) {
						tv_date_to.setText(TimeUtil.getStringFromDate(date, "yyyy-MM-dd"));
					}
				});
				dialog2.show();
				break;
			case R.id.next_sure:
				showPanel();
				break;
			case R.id.btn_filter_confirm:
				if(dialog_panel!=null){dialog_panel.dismiss();}
				refreshData();
				startTime = tv_date_from.getText().toString().trim();
				endTime = tv_date_to.getText().toString().trim();
				break;
			case R.id.btn_cancel:
				if(dialog_panel!=null){dialog_panel.dismiss();}
				break;
			default:break;
		}
	}


	private void showPanel() {
		dialog_panel = new AlertDialog.Builder(mContext).create();
		dialog_panel.show();
		Window window = dialog_panel.getWindow();

		WindowManager.LayoutParams lp =window.getAttributes();
		lp.x=0;
		lp.y=150;

		// 设置布局
		window.setContentView(R.layout.dialog_verification_record_filter);
		// 设置宽高
		window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
		// 设置弹出的动画效果
		// show at bottom
		window.setGravity(Gravity.TOP);

		ly_time_zone = (LinearLayout) window.findViewById(R.id.ly_time_zone);
		tv_date_from = (TextView) window.findViewById(R.id.tv_date_from);
		tv_date_to = (TextView) window.findViewById(R.id.tv_date_to);
		tv_date_from.setOnClickListener(this);
		tv_date_to.setOnClickListener(this);

		window.findViewById(R.id.btn_filter_confirm).setOnClickListener(this);
		window.findViewById(R.id.btn_cancel).setOnClickListener(this);

		reflashPanel();

	}


	private void reflashPanel(){

		ly_time_zone.setVisibility(View.VISIBLE);

		tv_date_from.setText(TimeUtil.getStringFromDate(panel_dateFrom, "yyyy-MM-dd"));
		tv_date_to.setText(TimeUtil.getStringFromDate(panel_dateTo, "yyyy-MM-dd"));

	}

}
